package mq

import (
	"context"

	amqp "github.com/rabbitmq/amqp091-go"
)

type Message = amqp.Publishing

type Publishing struct {
	Message   amqp.Publishing
	Exchange  string
	RouterKey string
	Mandatory bool
	Immediate bool
}

// PublishWithContext 发布消息, 创建新 channel (结束关闭 channel) 并尝试 declare queue, 错误转为已定义错误
func (mq *MessageQueue) PublishWithContext(
	ctx context.Context, queueConfig QueueDeclareConfig, message Publishing,
) error {
	if ch, _, err := mq.DeclareQueue(queueConfig); err != nil {
		return err
	} else {
		defer ch.Close()
		return mq.PublishDeclaredQueueWithContext(ctx, ch, message)
	}
}

// PublishDeclaredQueueWithContext 发布已声明的队列消息, 错误转为已定义错误, 不关闭 channel
func (mq *MessageQueue) PublishDeclaredQueueWithContext(
	ctx context.Context, ch *amqp.Channel, message Publishing,
) error {
	if err := ch.PublishWithContext(
		ctx, message.Exchange, message.RouterKey,
		message.Mandatory, message.Immediate, message.Message,
	); err != nil {
		return ErrPublish
	}

	return nil
}
